package com.cx.common.util;

import com.cx.common.cons.CharacterCons;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author flysand
 * @package com.cx.common.util
 * @date 2021-11-12 21:39
 * @des IpUtils: IP工具类
 */
public class IpUtils {

    private final static Logger logger = LoggerFactory.getLogger(IpUtils.class);

    private static final String LOCALHOST = "127.0.0.1";

    private static final String INTERNAL_HOST = "0:0:0:0:0:0:0:1";

    private static final String UNKNOWN = "unknown";

    public static String getIp(HttpServletRequest request) {
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals(LOCALHOST) || ipAddress.equals(INTERNAL_HOST)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inetAddress = null;
                    try {
                        inetAddress = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inetAddress != null ? inetAddress.getHostAddress() : null;
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null) {
                ipAddress = ipAddress.split(CharacterCons.COMMA)[0];
            }

        } catch (Exception e) {
            ipAddress = "";
        }
        logger.debug("ip:" + ipAddress);
        return ipAddress;
    }

    public static String getBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        UserAgent ua = UserAgent.parseUserAgentString(userAgent);
        return ua.getBrowser().getName() + " " + ua.getBrowserVersion();
    }
}
